package com.atguigu.exam.tools;

import com.atguigu.exam.entity.Appointment;
import com.atguigu.exam.service.AppointmentService;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AppointmentTools {

    @Autowired
    private AppointmentService appointmentService;

    @Tool(name="预约老师答疑", value = "根据参数，先执行工具方法queryDepartment查询是否可预约，并直接给用户回答是否可预约，" +
            "并让用户确认所有预约信息，用户确认后再进行预约。")
    public String bookAppointment(Appointment appointment){
        // 先检查是否有档期
        boolean hasSchedule = queryDepartment(
                appointment.getClazz(),
                appointment.getDate(),
                appointment.getTime(),
                appointment.getTeacherName()
        );

        if (!hasSchedule) {
            return "该时段已被预约，请选择其他时间";
        }

        // 查找数据库中是否包含对应的预约记录
        Appointment appointmentDB = appointmentService.getOne(appointment);

        if(appointmentDB == null){
            appointment.setId(null);//防止大模型幻觉设置了id
            if(appointmentService.save(appointment)){
                return "预约成功";
            }else{
                return "预约失败，请稍后重试";
            }
        }

        return "您与相同的老师和时间已有预约";
    }

    @Tool(name="取消预约", value = "根据参数，查询预约是否存在，如果存在则删除预约记录并返回取消预约成功，否则返回取消预约失败，" +
            "如果用户没有提供具体的老师姓名，请从向量数据库中找到合适的老师，并推荐给用户。")
    public String cancelAppointment(Appointment appointment){
        Appointment appointmentDB = appointmentService.getOne(appointment);
        if(appointmentDB != null){
            //删除预约记录
            if(appointmentService.removeById(appointmentDB.getId())){
                return "取消预约成功";
            }else{
                return "取消预约失败";
            }
        }

        //取消失败
        return "您没有预约记录，请核对预约老师和时间";
    }

    @Tool(name = "查询是否有档期", value="根据学科名称，日期，时间和老师名称查询该老师是否有空档期，并返回给用户")
    public boolean queryDepartment(
            @P(value = "学科名称") String clazzName,
            @P(value = "日期") String date,
            @P(value = "时间，可选值：上午、下午") String time,
            @P(value = "老师名称", required = false) String teacherName
    ) {

        // 构建查询条件
        Appointment queryAppointment = new Appointment();
        queryAppointment.setClazz(clazzName);
        queryAppointment.setDate(date);
        queryAppointment.setTime(time);

        // 如果提供了老师名称，就按老师名称查询
        if (teacherName != null && !teacherName.trim().isEmpty()) {
            queryAppointment.setTeacherName(teacherName);
        }

        // 查询是否已存在预约记录
        Appointment existingAppointment = appointmentService.getOne(queryAppointment);

        // 返回查询结果：true表示有档期（没有冲突预约），false表示没有档期（已有预约）
        boolean hasSchedule = (existingAppointment == null);

        System.out.println("档期查询结果：" + (hasSchedule ? "有档期" : "无档期"));
        return hasSchedule;
    }
}